import { Route, Routes, Navigate } from "react-router-dom";
import MenuList from "./MenuList";
import Login from "./Login";
import UserList from "./UserList";
import SpeechSynth from "./SpeechSynth";
import Test from "./Test";
import CbChat from "./CbChat";
import ZpChat from "./ZpChat";
import util from "./common/Util";
import constants from "./common/Constants";
import { Toast } from "antd-mobile";
import Game from "./Game";
import MXChat from "./MXChat";
import MXT2A from "./MXT2A";

function Auth({ children }) {
  const token = localStorage.getItem("token");
  if (token) {
    util.postForm(
      constants.baseUrl + "/app/validateByToken",
      { token },
      (e) => {
        if (e.code !== 0) {
          localStorage.removeItem("token");
        }
      }
    );
    return children;
  } else {
    Toast.show({
      content: "登录状态过期，请重新登录！",
      position: "center",
    });
    return <Navigate to="/login" replace />;
  }
}

function AppRouter() {
  return (
    <div>
      <Routes>
        <Route
          path="/menuList"
          element={
            <Auth>
              <MenuList />
            </Auth>
          }
        ></Route>
        <Route path="/login" element={<Login />}></Route>
        <Route
          path="/userList"
          element={
            <Auth>
              <UserList />
            </Auth>
          }
        ></Route>

        <Route
          path="/speechSynth"
          element={
            <Auth>
              <SpeechSynth />
            </Auth>
          }
        ></Route>

        <Route
          path="/test"
          element={
            <Auth>
              <Test />
            </Auth>
          }
        ></Route>

        <Route
          path="/cbChat"
          element={
            <Auth>
              <CbChat />
            </Auth>
          }
        ></Route>

        <Route
          path="/zpChat"
          element={
            <Auth>
              <ZpChat />
            </Auth>
          }
        ></Route>

        <Route
          path="/game"
          element={
            <Auth>
              <Game />
            </Auth>
          }
        ></Route>

        <Route
          path="/mxChat"
          element={
            <Auth>
              <MXChat />
            </Auth>
          }
        ></Route>

        <Route
          path="/mxT2a"
          element={
            <Auth>
              <MXT2A />
            </Auth>
          }
        ></Route>

        <Route
          path="*"
          element={
            <Auth>
              <MenuList />
            </Auth>
          }
        ></Route>
      </Routes>
    </div>
  );
}

export default AppRouter;
